<template>
	<view class="pages-find" v-if="isLoad">
		<!-- #ifndef H5 -->
		<uni-nav-bar :fixed="true" :shadow="false" :statusBar="true" title="发现" color="#ffffff"
			:backgroundColor="primaryColor">
		</uni-nav-bar>
		<view :style="{height:`${configInfo.navBarHeight}px`}"></view>
		<fixed :top="configInfo.navBarHeight">
		<!-- #endif -->
		<!-- #ifdef H5 -->
		<fixed>
		<!-- #endif -->
			<tab @change="handerTabChange" :list="tabList" :activeIndex="activeIndex*1" 
				:width="100/tabList.length + '%'" height="100rpx"></tab>
			<view class="b-1px-b"></view>
		</fixed>
		<view class="mt-sm fill-base find-list" v-for="(item,index) in list.data" :key="index">
			<view class="find-item b-1px-b">
				<view class="find-item-top flex-between">
					<view class="flex">
						<image :src="item.is_hide==0 ? item.avatarUrl : avatarUrl" mode="aspectFill" class="item-image radius-16"></image>
						<view class="flex-center">
							<view class="pl-md">
								<view class="f-title text-bold">{{item.is_hide==0 ? item.nickName : `匿名用户`}}</view>
								<view class="f-icontext c-caption flex-y-center">{{item.address | addressMatch}}<text class="pl-md">{{item.read_time}}</text></view>
							</view>
						</view>
					</view>
					<view class="f-desc">{{item.distance | handleDistance}} km</view>
				</view>
				<view class="f-min-title pre-wrap" :class="!item.isEllipsis ? 'ellipsis-3' : ''" style="line-height: 22px;">{{item.content}}</view>
				<view class="f-min-title abs pre-wrap" :class="`content`+index" style="line-height: 22px;z-index: -1;top: 0;">{{item.content}}</view>
				<view class="f-caption mt-md" :style="{color:primaryColor}" @tap.stop="updateMore(index)">{{item.isMore ? `展开` : `收起`}}</view>
				<view class="flex-center">
					<view class="find-images flex-warp">
						<block v-for="(citem,index) in item.img" :key="index">
							<block v-if="item.img.length == 1">
								<image :src="citem" mode="aspectFill" class="find-images-1 radius-16" @tap.stop="$util.previewImage({current:citem,urls:item.img})"></image>
							</block>
							<block v-if="item.img.length > 1">
								<image :src="citem" mode="aspectFill" class="images-item radius-16" @tap.stop="$util.previewImage({current:citem,urls:item.img})"></image>
							</block>
						</block>
					</view>
				</view>
				<view class="find-time radius-16 flex-y-center">
					<text class="f-desc pl-md pr-md">剩余</text>
					<min-countdown :newtargetTime="item.start_time" :isPlay="true" :type="3"></min-countdown>
				</view>
				<view class="pt-lg flex-between">
					<view class="flex-y-baseline">
						<view class="f-sm-title" :style="{color:primaryColor}">{{item.price}}</view>
						<view class="f-caption">元/单</view>
					</view>
					<view class="c-base text-center f-desc item-btn" 
					:style="{backgroundColor:primaryColor}" 
					@tap.stop="orderTaking(item.id)"
					v-if="userPageType == 2">接单</view>
				</view>
				
				<!-- <view class="pt-sm f-desc" style="color: #8A98AF;" v-if="item.order_code">订单编号: {{item.order_code}}</view> -->
			</view>
		</view>
		<load-more :noMore="list.current_page>=list.last_page&&list.data.length>0" :loading="loading" v-if="loading">
		</load-more>
		<abnor v-if="!loading&&list.data.length<=0&&list.current_page==1"></abnor>
		<view class="space-footer"></view>
		
		<auth :needAuth="userInfo && (!userInfo.phone || !userInfo.nickName)" :must="true"
			:type="!userInfo.phone ? 'phone' : 'userInfo'" @go="$util.goUrl({url:`/find/pages/index`})">
		<view class="find-release box-shadow-mini flex-center fill-base">
			<view class="text-center">
				<i class="iconfont iconedit-fill"></i>
				<view class="f-ms-little c-desc">发布</view>
			</view>
		</view>
		</auth>
		<!--附近排序-->
		<w-picker mode="selector" :options="distanceList" :themeColor="primaryColor"
			:visible.sync="showDistance" @confirm="selectConfirm($event , 'distance')">
		</w-picker>
		<!--服务分类-->
		<w-picker mode="selector" :options="skill" :themeColor="primaryColor" 
			:visible.sync="showServer" @confirm="selectConfirm($event , 'ser_id')" :defaultProps="serverProps">
		</w-picker>
		<!--价格区间-->
		<w-picker mode="selector" :options="priceList" :themeColor="primaryColor" 
			:visible.sync="showPrice" @confirm="selectConfirm($event , 'price')">
		</w-picker>
		
		<view :style="{height: `${configInfo.tabbarHeight}px`}"></view>
		<tabbar :cur="7"></tabbar>
	</view>
</template>

<script>
	import {
		mapState,
		mapActions,
		mapMutations
	} from "vuex"
	import tabbar from "@/components/tabbar.vue"
	export default {
		components: {
			tabbar
		},
		data() {
			return {
				loading:true,
				isLoad:false,
				serverList:[],
				showDistance:false,
				showServer:false,
				showPrice:false,
				serverProps:{
					label:"name",
					value:"id"
				}
			}
		},
		computed: mapState({
			pageActive: state => state.find.pageActive,
			activeIndex: state => state.find.activeIndex,
			tabList: state => state.find.tabList,
			param: state => state.find.param,
			list: state => state.find.list,
			skill: state => state.find.skill,
			distanceList: state => state.find.distanceList,
			priceList: state => state.find.priceList,
			primaryColor: state => state.config.configInfo.primaryColor,
			subColor: state => state.config.configInfo.subColor,
			configInfo: state => state.config.configInfo,
			avatarUrl: state => state.config.avatarUrl,
			userInfo: state => state.user.userInfo,
			location: state => state.user.location,
			userPageType: state => state.user.userPageType,
		}),
		async onLoad(options) {
			this.initIndex()
			if(this.skill.length == 0){
				this.getSkill()
			}
		},
		
		onPullDownRefresh() {
			// #ifndef APP-PLUS
			uni.showNavigationBarLoading()
			// #endif
			this.initIndex(true);
			uni.stopPullDownRefresh()
		},
		onReachBottom() {
			if (this.list.current_page >= this.list.last_page || this.loading) return;
			this.loading = true;
			this.param.page += 1
			this.updateFindItem({
				key: 'param',
				val: this.param
			})
			this.updateList(this.param)
		},
		methods: {
			...mapActions(['getFindList','getConfigInfo','getSkill']),
			...mapMutations(['updateFindItem','updateUserItem']),
			initRefresh(){
				this.updateList(this.param)
			},
			async initIndex(refresh = false) {
				// #ifdef H5
				if (!refresh && this.$jweixin.isWechat()) {
					await this.$jweixin.initJssdk();
					this.toAppShare()
				}
				// #endif
				if (!this.configInfo.id || refresh) {
					await this.getConfigInfo()
				}
				await this.getLocation()
			},
			handerTabChange(index) {
				console.log(index ,'=========>handerTabChange')
				this.updateFindItem({
					key: 'activeIndex',
					val: index
				})
				uni.pageScrollTo({
					scrollTop: 0
				})
				if(index == 0){
					this.showDistance = true
				}else if(index == 1){
					this.showServer = true
				}else if(index == 2){
					this.showPrice = true
				}
			},
			toAppShare() {
				let {
					id: pid
				} = this.userInfo
				let title = '发现'
				let page_url = window.location.href
				if (page_url.includes('?pid=')) {
					page_url = page_url.split('?pid=')[0]
				}
				let href = `${page_url}?pid=${pid}`
				let imageUrl = ''
				this.$jweixin.wxReady(() => {
					this.$jweixin.showOptionMenu()
					this.$jweixin.shareAppMessage(title, '', href, imageUrl)
					this.$jweixin.shareTimelineMessage(title, href, imageUrl)
				})
			},
			async selectConfirm(e , type){
				this.$util.showLoading()
				console.log(e , type)
				let param = this.$util.deepCopy(this.param)
				if(type == 'price'){
					param = {...param , ...e.value}
				}else{
					param[type] = e.value
				}
				param.page = 1
				this.updateFindItem({
					key: 'param',
					val: param
				})
				
				await this.updateList(param)
				console.log(this.list.data)
				this.$util.hideAll()
			},
			async updateList(param){
				await this.getFindList(param)
				setTimeout(()=>{
					this.list.data.forEach((item,index) => {
						item.new_start_time = item.start_time.replace(/-/g,'/')
						setTimeout(()=>{
							uni.createSelectorQuery().select('.content'+index).boundingClientRect(data => { //目标位置的节点，类class或者id
								console.log(data , '目标位置的节点，类class或者id')
								item.isMore = data && data.height > 66 ? true : false
							}).exec();
						},100)
					})
				},500)
			},
			async getLocation(){
				let {
					location
				} = this
				if (!location.lat) {
					// #ifdef H5
					if (this.$jweixin.isWechat()) {
						this.$util.showLoading()
						// await this.$jweixin.initJssdk();
						await this.$jweixin.wxReady2();
						let {
							latitude: lat = 0,
							longitude: lng = 0
						} = await this.$jweixin.getWxLocation()
						location = {
							lng,
							lat,
							address: '定位失败',
							province: '',
							city: '',
							district: ''
						}
						if (lat && lng) {
							let key = `${lat},${lng}`
							let data = await this.$api.base.getMapInfo({
								location: key
							})
							let {
								status,
								result
							} = JSON.parse(data)
							if (status == 0) {
								let {
									address,
									address_component
								} = result
								let {
									province,
									city,
									district
								} = address_component
								location = {
									lng,
									lat,
									address,
									province,
									city,
									district
								}
							}
						}
					}
					// #endif
					// #ifndef H5
					location = await this.$util.getBmapLocation()
					// #endif
					this.updateUserItem({
						key: 'location',
						val: location
					})
					this.$util.hideAll()
				}
				let {
					lng = 0,
						lat = 0
				} = location
				this.param.lat = lat
				this.param.lng = lng
				await this.updateFindItem({
					key: 'param',
					val: this.param
				})
				await this.updateList(this.param)
				this.loading = false
				this.isLoad = true
			},
			updateMore(index){
				let list = this.$util.deepCopy(this.list)
				list.data[index].isEllipsis = !list.data[index].isEllipsis
				list.data[index].isMore = !list.data[index].isMore
				console.log(list.data , index)
				this.updateFindItem({
					key: 'list',
					val: list
				})
			},
			// 接单
			async orderTaking(id){
				await this.$api.find.receivingOrder({id})
				this.$util.showToast({
					title: '接单成功'
				});
				this.initRefresh()
				setTimeout(()=>{
					this.$util.goUrl({url:`/technician/pages/invitation/list`})
				},1000)
			}
		},
		filters:{
			handleDistance(val){
				return (val/1000).toFixed(2)
			},
			addressMatch(val){
				if(!val) return ''
				var reg = /.+?(省|市|自治区|自治州|县|区)/g;
				let address = Array.from(val.match(reg))[1]
				return address
			}
		}
	}
</script>

<style lang="scss">
	.pages-find {
		.find-list{
			.find-item{
				padding-bottom: 30rpx;
			}
			padding: 0 30rpx;
			.find-item-top{
				height: 144rpx;
				.item-image{
					width: 84rpx;
					height: 84rpx;
				}
			}
			.find-images{
				padding: 25rpx 0;
				width: 680rpx;
				.find-images-1{
					width: 100%;
					height: 376rpx;
				}
				.images-item{
					width: 216rpx;
					height: 216rpx;
					margin-right: 16rpx;
					margin-bottom: 16rpx;
				}
				.images-item:nth-child(3n){
					margin-right: 0rpx;
				}
			}
			.find-time{
				height: 80rpx;
				background-color: #FFF9F9;
			}
			.item-btn{
				width: 120rpx;
				height: 56rpx;
				line-height: 56rpx;
				border-radius: 56rpx;
			}
		}
		.find-release{
			width: 77rpx;
			height: 77rpx;
			border-radius: 77rpx;
			position: fixed;
			right: 20rpx;
			bottom: 267rpx;
		}
	}
</style>
